﻿using LoveEatRabbit.API.Read.Applications.Commands;
using LoveEatRabbit.API.Read.DTOS;
using LoveEatRabbit.Domain.RBAC;
using LoveEatRabbit.ErrorCode;
using LoveEatRabbit.Infrastructure.Interfaces;
using LoveEatRabbit.Infrastructure.Migrations;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace LoveEatRabbit.API.Read.Applications.CommandHandlers
{
    /// <summary>
    /// 用户登录请求命令
    /// </summary>
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<UserDTO>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IBaseRespository<UserModel> userRep;
        /// <summary>
        /// 角色仓储
        /// </summary>
        private readonly IBaseRespository<RoleModel> roleRep;
        /// <summary>
        /// 角色权限仓储
        /// </summary>
        private readonly IBaseRespository<RolePermissionModel> rolePermissionRep;
        /// <summary>
        /// 权限仓储
        /// </summary>
        private readonly IBaseRespository<PermissionModel> permissionRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRep">用户仓储</param>
        /// <param name="roleRep">角色仓储</param>
        /// <param name="permissionRep">权限仓储</param>
        /// <param name="rolePermissionRep">角色权限仓储</param>
        public LoginQueryCommandHandler(IBaseRespository<UserModel> userRep, 
            IBaseRespository<RoleModel> roleRep, 
            IBaseRespository<RolePermissionModel> rolePermissionRep,
            IBaseRespository<PermissionModel> permissionRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.permissionRep = permissionRep;
        }
        /// <summary>
        /// 请求处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIResult<UserDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result = new APIResult<UserDTO>();
            result.Code = APIResultCode.登陆成功;
            result.Message = APIResultCode.登陆成功.ToString();

            var res = from a in userRep.GetAll()
                      join b in roleRep.GetAll() on a.RoleId equals b.RoleId
                      join c in rolePermissionRep.GetAll() on b.RoleId equals c.RoleId
                      join d in permissionRep.GetAll() on c.PermissionId equals d.PermissionId
                      where a.UserName == request.UserName
                      select new UserDTO
                      {
                          UserId = a.UserId,
                          UserName=a.UserName,
                          UserPass=a.UserPass,
                          RoleId = b.RoleId,
                          UserNickname = a.UserNickname,
                          RoleName = b.RoleName,
                          RPId = c.RPId,
                          PermissionId = d.PermissionId,
                          PermissionName = d.PermissionName,
                          PermissionURL = d.PermissionURL,
                      };

            var entity=res.FirstOrDefault();
            if (entity == null)
            {
                result.Code = APIResultCode.登录失败;
                result.Message = APIResultCode.登录失败.ToString() + "用户不存在";
                return Task.FromResult(result);    
            }
            request.UserPass = request.UserPass.GetMD5();
            if (entity.UserPass != request.UserPass)
            {
                result.Code = APIResultCode.登录失败;
                result.Message = APIResultCode.登录失败.ToString() + "密码错误";
                return Task.FromResult(result);
            }

            result.Code = APIResultCode.登陆成功;
            result.Message = APIResultCode.登陆成功.ToString();
            entity.Token = CreateTokenString();
            result.Data = entity;


            return Task.FromResult(result);
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
